import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../common/entity/share.dart';
import '../common/entity/user.dart';
import '../common/services/share_service.dart';
import 'user_provider.dart';

/// Share状态类
class ShareState {
  final List<ShareEntity> shares;
  final bool isLoading;
  final String? error;

  const ShareState({
    this.shares = const [],
    this.isLoading = false,
    this.error,
  });

  ShareState copyWith({
    List<ShareEntity>? shares,
    bool? isLoading,
    String? error,
  }) {
    return ShareState(
      shares: shares ?? this.shares,
      isLoading: isLoading ?? this.isLoading,
      error: error,
    );
  }
}

/// Share状态管理器
class ShareNotifier extends StateNotifier<ShareState> {
  ShareNotifier() : super(const ShareState());

  /// 根据用户ID获取分享列表
  Future<void> loadSharesByUserId(String userId) async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final shares = await ShareService.getSharesByUserId(userId);

      // 按日期降序排序（最新的在前面）
      shares.sort(
        (a, b) => DateTime.parse(b.date).compareTo(DateTime.parse(a.date)),
      );

      await Future.delayed(const Duration(milliseconds: 300));

      state = state.copyWith(shares: shares, isLoading: false);
    } catch (e) {
      state = state.copyWith(isLoading: false, error: '加载分享失败: $e');
    }
  }

  /// 获取所有分享列表（用于社区页面）
  Future<void> loadAllShares() async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      await Future.delayed(const Duration(milliseconds: 250));

      final shares = await ShareService.getAllSharesFiltered();

      // 按日期降序排序（最新的在前面）
      shares.sort(
        (a, b) => DateTime.parse(b.date).compareTo(DateTime.parse(a.date)),
      );

      state = state.copyWith(shares: shares, isLoading: false);
    } catch (e) {
      state = state.copyWith(isLoading: false, error: '加载所有分享失败: $e');
    }
  }

  /// 根据日期过滤分享
  List<ShareEntity> getSharesByDate(DateTime date) {
    return state.shares.where((share) {
      final shareDate = DateTime.parse(share.date);
      return shareDate.year == date.year &&
          shareDate.month == date.month &&
          shareDate.day == date.day;
    }).toList();
  }

  // 浏览量+1
  Future<void> incrementViewCount(String shareId) async {
    try {
      // 首先尝试从当前状态中找到分享
      ShareEntity? share;
      try {
        share = state.shares.firstWhere((share) => share.id == shareId);
      } catch (e) {
        // 如果在当前状态中找不到，从数据库中获取
        final shares = await ShareService.getSharesById(shareId);
        if (shares.isNotEmpty) {
          share = shares.first;
        }
      }

      if (share != null) {
        final updatedShare = share.copyWith(browses: share.browses + 1);
        await ShareService.updateShare(updatedShare);

        // 更新状态中的分享（如果存在的话）
        final shareIndex = state.shares.indexWhere((s) => s.id == shareId);
        if (shareIndex != -1) {
          state = state.copyWith(
            shares: state.shares
                .map((s) => s.id == shareId ? updatedShare : s)
                .toList(),
          );
        }
      }
    } catch (e) {
      debugPrint('增加浏览量失败: $e');
    }
  }

  /// 创建新分享
  Future<bool> createShare(ShareEntity share) async {
    try {
      // 保存分享到数据库
      final success = await ShareService.createShare(share);

      if (success) {
        // 更新状态，将新分享添加到列表开头
        final updatedShares = [share, ...state.shares];
        state = state.copyWith(shares: updatedShares);
        return true;
      }

      return false;
    } catch (e) {
      state = state.copyWith(error: '创建分享失败: $e');
      return false;
    }
  }

  /// 清除错误信息
  void clearError() {
    state = state.copyWith(error: null);
  }
}

/// Share状态 Provider
final shareProvider = StateNotifierProvider<ShareNotifier, ShareState>(
  (ref) => ShareNotifier(),
);

/// 根据用户ID获取分享列表的Provider
final userSharesProvider = FutureProvider.family<List<ShareEntity>, String>((
  ref,
  userId,
) async {
  final shares = await ShareService.getSharesByUserId(userId);
  // 按日期降序排序（最新的在前面）
  shares.sort(
    (a, b) => DateTime.parse(b.date).compareTo(DateTime.parse(a.date)),
  );
  return shares;
});

/// 根据日期过滤分享的Provider
final sharesByDateProvider = Provider.family<List<ShareEntity>, DateTime>((
  ref,
  date,
) {
  final shareState = ref.watch(shareProvider);
  return shareState.shares.where((share) {
    final shareDate = DateTime.parse(share.date);
    return shareDate.year == date.year &&
        shareDate.month == date.month &&
        shareDate.day == date.day;
  }).toList();
});

/// 获取分享作者信息的Provider
/// 监听用户信息变化，确保作者信息实时更新
final shareAuthorProvider = Provider.family<UserEntity?, ShareEntity>((
  ref,
  share,
) {
  // 监听用户状态变化，确保用户信息更新后作者信息也会更新
  ref.watch(userProvider);

  // 使用ShareService的统一方法获取作者信息
  return ShareService.getShareAuthor(share);
});
